package cn.swu.lyx.homework4.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.swu.lyx.homework4.R
import cn.swu.lyx.homework4.dao.UserDao
import cn.swu.lyx.homework4.utils.Connection


class MainActivity : AppCompatActivity() {
    val TAG = "mysql-MainActivity"
    val context=this
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Connection.mymysql()
    }
    fun reg(view: View?) {
        val intent=Intent(this, register::class.java)
        startActivity(intent)
    }

    /**
     * function: 登录
     */
    fun login(view: View?) {
      val EditTextAccount = findViewById<EditText>(R.id.uesrAccount)
      val EditTextPassword = findViewById<EditText>(R.id.userPassword)
      object : Thread() {
          override fun run() {
              val userDao = UserDao()
              val msg =
                  userDao.login(EditTextAccount.text.toString(), EditTextPassword.text.toString())
              hand1.sendEmptyMessage(msg)
          }
      }.start()

    }

    @SuppressLint("HandlerLeak")
    val hand1: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            if (msg.what == 0) {
                Toast.makeText(applicationContext, "登录失败", Toast.LENGTH_LONG).show()
            } else if (msg.what == 1) {
                Toast.makeText(applicationContext, "登录成功", Toast.LENGTH_LONG).show()
                val intent=Intent(context, BottomActivity::class.java)
                startActivity(intent)
            } else if (msg.what == 2) {
                Toast.makeText(applicationContext, "密码错误", Toast.LENGTH_LONG).show()
            } else if (msg.what == 3) {
                Toast.makeText(applicationContext, "账号不存在", Toast.LENGTH_LONG).show()
            }
        }
    }

    companion object {
        private const val TAG = "mysql-MainActivity"
    }
}
